﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using PQ.Util;
using System.Globalization;
using System.Threading;
namespace PQ
{
    public partial class ConfigForm : Form
    {
      
        public AccessUtil accessUtil;
        public Configuration cfg;
        public PQAlgo pqAlgo;
        Thread sampleThread;
        Thread calcAndSaveThread;
        public bool isStart = false;

        public ConfigForm()
        {
            cfg = new Configuration();
            InitializeComponent();
            InitializeMyComponent();
        }

        private void InitializeMyComponent()
        {
            this.dataGridView1.RowCount = 11;
            dataGridView1.Columns[0].Width = 200;
            dataGridView1[0, 0].Value = "公司:";
            dataGridView1[0, 1].Value = "部门:";
            dataGridView1[0, 2].Value = "联系:";
            dataGridView1[0, 3].Value = "测量原因:";
            dataGridView1[0, 4].Value = "参照";
            this.rmsComboBox.SelectedIndex = 0;
            this.HarmComboBox.SelectedIndex = 0;
            this.RatingFcomboBox.SelectedIndex = 0;
            this.sampleFreqComboBox.SelectedIndex = 6;
            this.triggerModeComboBox.SelectedIndex = 1;
            rangeComboBox.SelectedIndex = 0;
        }


        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void ConfigForm_Load(object sender, EventArgs e)
        {
          
            
        }

        private void close_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void domainUpDown1_SelectedItemChanged(object sender, EventArgs e)
        {

        }

        private void textBox2_Validating(object sender, CancelEventArgs e)
        {
            try
            {
                TextBox tb = ((TextBox)sender);
                int sec = Convert.ToInt32(tb.Text);
                if(String.Equals(tb.Tag.ToString(), "min") && sec < 0)
                 tb.Text = "0";
                   
                    
               if (String.Equals(tb.Tag.ToString() , "s") &&  (sec < 0 || sec > 60) )
               {
                   tb.Text ="0" ;
                }
            }
            catch(Exception ex)
            {
                ((TextBox)sender).Text = "0";
            }
        }

        private void textBox26_Validating(object sender, CancelEventArgs e)
        {
            try
            {
                double f = Convert.ToDouble(((TextBox)sender).Text);
               
            }
            catch (Exception ex)
            {
                ((TextBox)sender).Text = "1.00000";
            }
        }

        public void save_Click(object sender, EventArgs e)
        {

           
                if (DialogResult.OK == this.saveFileDialog1.ShowDialog())
                {
                    accessUtil = new AccessUtil(this.saveFileDialog1.FileName);
                    FormToCfg();
                    accessUtil.saveConfiguration(cfg);
                    this.saveFileDialog1.Dispose();
                    this.startButton.Enabled = true;
                    this.saveButton.Enabled = false;
                }
           
            
        }
        private void FormToCfg()
        {
            for(int i = 0;i <  dataGridView1.RowCount;i++)
            {
                if (dataGridView1[0, i].Value != null)
                {
                    if (dataGridView1[0, i].Value.ToString().Trim() != "")
                    {
                        cfg.addBasicInfo(dataGridView1[0, i].Value.ToString(),dataGridView1[1, i].Value == null ? "":dataGridView1[1, i].Value.ToString()) ;
                    }
                }
            }
            cfg[Configuration.RatingU] = this.RatingUTextBox.Text;
            cfg[Configuration.RatingF] = this.RatingFcomboBox.SelectedItem.ToString();
            cfg[Configuration.RMSInterval] = this.rmsComboBox.SelectedItem.ToString();
            cfg[Configuration.HarmonicsInterval] = this.HarmComboBox.SelectedItem.ToString();
            cfg[Configuration.CustomInterval] =(Convert.ToInt32(this.MinTextBox.Text) * 60 + Convert.ToInt32(this.SecTextBox.Text))+"";
            cfg[Configuration.SampleFreq] = this.sampleFreqComboBox.SelectedItem.ToString();
            cfg[Configuration.TriggerMode] = this.triggerModeComboBox.SelectedItem.ToString();
            cfg[Configuration.Range] = rangeComboBox.SelectedItem.ToString();
            if (this.startTimePicker.Checked)
            {
                cfg[Configuration.StartTime] = startTimePicker.Value.ToString(cfg.format, DateTimeFormatInfo.InvariantInfo);
            }
            if (this.stopTimePicker.Checked)
            {
                cfg[Configuration.StopTime] = stopTimePicker.Value.ToString(cfg.format, DateTimeFormatInfo.InvariantInfo);
            }
            cfg.setHardwareConfig("CH1", this.measCH1TextBox.Text, Convert.ToDouble(this.factorCH1TextBox.Text));
            cfg.setHardwareConfig("CH2", this.measCH2TextBox.Text, Convert.ToDouble(this.factorCH2TextBox.Text));
            cfg.setHardwareConfig("CH3", this.measCH3TextBox.Text, Convert.ToDouble(this.factorCH3TextBox.Text));
            cfg.setHardwareConfig("CH4", this.measCH4TextBox.Text, Convert.ToDouble(this.factorCH4TextBox.Text));
            cfg.setHardwareConfig("CH5", this.measCH5TextBox.Text, Convert.ToDouble(this.factorCH5TextBox.Text));
            cfg.setHardwareConfig("CH6", this.measCH6TextBox.Text, Convert.ToDouble(this.factorCH6TextBox.Text));
            cfg.setHardwareConfig("CH7", this.measCH7TextBox.Text, Convert.ToDouble(this.factorCH7TextBox.Text));
            cfg.setHardwareConfig("CH8", this.measCH8TextBox.Text, Convert.ToDouble(this.factorCH8TextBox.Text));
            cfg.setHardwareConfig("CH9", this.measCH9TextBox.Text, Convert.ToDouble(this.factorCH9TextBox.Text));


        }
        private void CfgToForm()
        {
            stopTimePicker.Value = cfg.stopTime;
            startTimePicker.Value = cfg.startTime;
            dataGridView1.RowCount = 0;
            dataGridView1.RowCount = 11;
            for (int i = 0; i < cfg.getBasicInfoSize(); i++)
            {
                dataGridView1[0, i].Value = cfg.getBasicInfoName(i);
                dataGridView1[1, i].Value = cfg.getBasicInfoValue(i);
            }
            setCH(cfg.indexUA, "UA", cfg.Fua);
            setCH(cfg.indexUB, "UB", cfg.Fub);
            setCH(cfg.indexUC, "UC", cfg.Fuc);
            setCH(cfg.indexUN, "UN", cfg.Fun);
            setCH(cfg.indexUZ, "UZ", cfg.Fuz);
            setCH(cfg.indexIA, "IA", cfg.Fia);
            setCH(cfg.indexIB, "IB", cfg.Fib);
            setCH(cfg.indexIC, "IC", cfg.Fic);
            setCH(cfg.indexIN, "IN", cfg.Fin);
            this.RatingUTextBox.Text = cfg.ratingU + "";
            this.UnPhPhTextBox.Text = cfg.ratingU * 1.732 + "";
            if (cfg.rmsInterval == 200.00)
            {
                this.rmsComboBox.SelectedIndex = 0;
            }
            else
            {
                this.rmsComboBox.SelectedIndex = 1;
            }

            if (cfg.harmonicsInterval == 200.00)
            {
                this.HarmComboBox.SelectedIndex = 0;
            }
            else
            {
                this.HarmComboBox.SelectedIndex = 1;
            }
            if (cfg.ratingF == 50.00)
            {
                this.RatingFcomboBox.SelectedIndex = 0;
            }
            else
            {
                this.RatingFcomboBox.SelectedIndex = 1;
            }
 
            MinTextBox.Text = cfg.customInterval / 60 +"";
            SecTextBox.Text = cfg.customInterval % 60 + "";
            this.sampleFreqComboBox.SelectedIndex = USB1612M.genSampleFreqIndex(cfg.sampleFreqStr) - 1;
            this.triggerModeComboBox.SelectedIndex = cfg.triggerMode;
            if (cfg.range == 10.0)
            {
                rangeComboBox.SelectedIndex = 0;
            }
            else if (cfg.range == 5.0)
            {
                rangeComboBox.SelectedIndex = 1;
            }
            
        }
        public void showConfig(Configuration cfg)
        {
            this.cfg = cfg;
            CfgToForm();
            this.Show();
            this.startButton.Enabled = false;
        }
        private void setCH(int index,String measuredName,double factor)
        {
            switch(index)
            {
                case 0:
                    this.measCH1TextBox.Text = measuredName;
                    this.factorCH1TextBox.Text = factor + "";
                    break;
                case 1:
                    this.measCH2TextBox.Text = measuredName;
                    this.factorCH2TextBox.Text = factor + "";
                    break;
                case 2:
                    this.measCH3TextBox.Text = measuredName;
                    this.factorCH3TextBox.Text = factor + "";
                    break;
                case 3:
                    this.measCH4TextBox.Text = measuredName;
                    this.factorCH4TextBox.Text = factor + "";
                    break;
                case 4:
                    this.measCH5TextBox.Text = measuredName;
                    this.factorCH5TextBox.Text = factor + "";
                    break;
                case 5:
                    this.measCH6TextBox.Text = measuredName;
                    this.factorCH6TextBox.Text = factor + "";
                    break;
                case 6:
                    this.measCH7TextBox.Text = measuredName;
                    this.factorCH7TextBox.Text = factor + "";
                    break;
                case 7:
                       this.measCH8TextBox.Text = measuredName;
                    this.factorCH8TextBox.Text = factor + "";
                    break;
                case 8:
                    this.measCH9TextBox.Text = measuredName;
                    this.factorCH9TextBox.Text = factor + "";
                    break;

            }
        }
        private void RatingUTextBox_Validating(object sender, CancelEventArgs e)
        {
            TextBox tb = ((TextBox)sender);

            try
            {
                double u = Convert.ToDouble(tb.Text);
                if (u < 0)
                {

                    tb.Text = "220.00";
                }
                else
                {
                    this.UnPhPhTextBox.Text = u * 1.732 + "";
                }
            }
            catch (Exception ex)
            {
                tb.Text = "220.00";
            }
            
        }

        private void startButton_Click(object sender, EventArgs e)
        {
            startSample();
        }

        private void stopButton_Click(object sender, EventArgs e)
        {
            stopSample();
            
        }

        public void stopSample()
        {
            USB1612M u = USB1612M.getUSB1612M();
            u.StopSample();
            pqAlgo.stop();
            stopButton.Enabled = false;
            isStart = false;
        }
        public void startSample()
        {
            USB1612M u = USB1612M.getUSB1612M(cfg);
            if (u.OpenDevice())
            {
                // u.StartSample();

                sampleThread = new Thread(new ThreadStart(u.StartSample));
                //线程优先级设为最高
                sampleThread.Priority = ThreadPriority.Highest;
                sampleThread.Start();

                pqAlgo = new PQAlgo(cfg, accessUtil);
                calcAndSaveThread = new Thread(new ThreadStart(pqAlgo.run));
                calcAndSaveThread.Start();
                startButton.Enabled = false;
                stopButton.Enabled = true;
                isStart = true;
            }
            else
            {
               // MessageBox.Show("打开设备失败，请检查驱动是否安装好和设备是否已经连接上。");
                sampleThread = new Thread(new ThreadStart(cfg.genData));
                //线程优先级设为最高
                sampleThread.Priority = ThreadPriority.Highest;
                sampleThread.Start();

                pqAlgo = new PQAlgo(cfg, accessUtil);
                calcAndSaveThread = new Thread(new ThreadStart(pqAlgo.run));
                calcAndSaveThread.Start();
                startButton.Enabled = false;
                stopButton.Enabled = true;
                isStart = true;
            }
        }
       
    }
}
